package com.likou.math;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.util.*;

public class KmainsUtil {
    public static KmainsNode[] kmainsNodes(KmainsNode [] kmainsNodes,int i) throws RuntimeException{
        if(i>kmainsNodes.length){
            throw new RuntimeException("无需聚点");
        }
        KmainsNode [] result = Arrays.copyOf(kmainsNodes,i);
        Map<KmainsNode, List<KmainsNode>> map = new HashMap<>(i);
        boolean flag;
        do {
            flag = true;
            map.clear();
            for (KmainsNode kmainsNode:result){
                map.put(kmainsNode,new ArrayList<>());
            }

            for (KmainsNode kmainsNode:kmainsNodes){
                KmainsNode temp = kmainsNode.minDistance(result);
                if(!map.containsKey(temp)){
                    map.put(temp,new ArrayList<>());
                }
                map.get(temp).add(kmainsNode);
            }

            for (int j = 0; j < result.length; j++) {
                if(!result[j].attributeEquals(map.get(result[j]),"聚点")){
                    flag = false;
                    result[j] = KmainsNode.avg(map.get(result[j]),"聚点");
                }
            }

        } while (flag);
        return result;
    }
}
